package cn.szsys.integration.repository;

import cn.szsys.integration.constants.AppConstant;
import cn.szsys.integration.dos.AccessorDO;
import cn.szsys.integration.mapper.AccessorMapper;
import cn.szsys.integration.runner.entity.Accessor;
import cn.szsys.integration.runner.entity.AuthorizationConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.repository.CrudRepository;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Repository;

/**
 * @author Ryan
 * @since 2025-05-15
 **/
@Repository
public class AccessorRepository extends CrudRepository<AccessorMapper, AccessorDO> {
    /**
     * 使用banner中加载的配置文件获取的数据
     */
    @Resource
    private Environment env;

    /**
     * 根据ak获取授权信息
     *
     * @param ak ak
     * @return {@link Accessor}
     * @author Ryan
     */
    @Cacheable(key = "#ak", value = "accessor")
    public Accessor getAccessorByAk(String ak) {
        LambdaQueryWrapper<AccessorDO> wrapper = Wrappers.lambdaQuery();
        AccessorDO accessorDO = this.baseMapper.selectOne(wrapper.eq(AccessorDO::getAk, ak));
        return null == accessorDO ? null : accessorDO.toAccessor();
    }

    /**
     * 更新缓存
     *
     * @param accessor accessor
     * @author Ryan
     */
    @CachePut(key = "#accessor.ak", value = "accessor")
    public void update(Accessor accessor) {
    }

    /**
     * 删除缓存
     *
     * @param ak ak
     * @author Ryan
     */
    @CachePut(key = "#ak", value = "accessor")
    public void delete(String ak) {
    }

    /**
     * 从spring环境变量中获取
     *
     * @param ak ak
     * @return {@link Accessor}
     * @author Ryan
     */
    public Accessor getAccessorByAkInFile(String ak) {
        AuthorizationConfig authorizationConfig = env.getProperty(AppConstant.DOWNSTREAM_CONFIGURATION, AuthorizationConfig.class);
        //根据ak获取信息
        return authorizationConfig.getAccessorByAk(ak);
    }
}
